var compareString = '';
var graphLetter = 't';
var graphPeriod = '3m';
var graphLetters = {'traffic':'t',
                   'reach':'r',
                   'page':'p',
                   'page_user':'u',
                   'bounce':'b',
                   'time':'s',
                   'search':'q'};
var part_stats = 0;
var part_whois = 0;

$(document).ready(function(){
	$("#update").click(function(){
		var width=$(document).width();
		var height=$(document).height();
		$('#opacity').css('width',width+'px');
		$('#opacity').css('height',height+'px');
		$('#opacity').css('display','block');
		$('#opacity').css('opacity','0.5');
		$('#image_loadder').css('display','block');
		$('#image_loadder').css("left",($(window).width()-100)/2+"px");
		$('#image_loadder').css("top",($(window).height()-100)/2+"px");
		setTimeout(function(){
			window.location = location.href;
		},60000);
		
		$.get(
				'/update',
				{name:graphDomain},
				function(data)
				{
					window.location = location.href+"?update=true";
				}
		);
	
	});
	
	
	$("#backlink").click(function(){
		$("#backlink_info").html("<img src='/images/ajax-loader.gif' style='text-align:center'/>");
		$.get(
				'/backlink',
				{
					name:graphDomain
				},
				function(data)
				{
					$("#backlink_info").html(data);
				}
		);
	});
	$("#index").click(function(){
		$("#index-page").html("<img src='/images/ajax-loader.gif' style='text-align:center'/>");
		$.get(
				'/index',
				{
					name:graphDomain
				},
				function(data)
				{
					$("#index-page").html(data);
				}
		);
	});
});

function showTab(tab, data, part)
{
	$('#tab_' + tab).addClass('current');
    if (null != data && typeof data != 'undefined') 
	{
		if ($.trim(part) == 2)
			$('#content_' + tab).append(data);
		else
			$('#content_' + tab).html(data);
    }
    $('#content_' + tab).slideDown();
}

$(document).ready(function(){
	$("#inlink").attr("href","/in-link/"+graphDomain)
	$("#selectPeriod").click(function() {
        graphPeriod = this.value;
	    updateGraphic();
	});

    $("#selectPeriod").change(function() {
		graphPeriod = this.value;
		updateGraphic();
	});
});	            


function viewGraphTab(tabName)
{
    $("li[id^=gr_]").removeClass("current");
    $("#gr_" + tabName).addClass("current");
    graphLetter = graphLetters[tabName];
    updateGraphic();
}

function compareTo(tabName)
{
    var compares = '';
    var inputs = $('.compare-to');
    var compareDomain;
    $.each(inputs, function(index, value) {
        compareDomain = $(value).attr('value');
        if ('' != compareDomain) {
            compares += '&u=' + compareDomain;
        }
    });
    compareString = compares;
    updateGraphic();
}
function updateGraphic()
{
    var grQuerySting = 'http://traffic.alexa.com/graph?&w=400&h=220&o=f&c=1&y='
                     + graphLetter
                     + '&b=ffffff&n=666666&r=' + graphPeriod + '&u=' + graphDomain
                     + compareString;
    
    $('#alexaGraphic').attr({'src':grQuerySting});
}

//Specify your actual API key here:
var API_KEY = 'AIzaSyB-aMH9_2JJCYCSRL578Vnqiio6faclchE';

//Specify the URL you want Page Speed results for here:
var URL_TO_GET_RESULTS_FOR="http://"+graphDomain;

var API_URL = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?';
var CHART_API_URL = 'http://chart.apis.google.com/chart?';

//Object that will hold the callbacks that process results from the
//Page Speed Online API.
var callbacks = {}

//Invokes the Page Speed Online API. The response will contain
//JavaScript that invokes our callback with the Page Speed results.
function runPagespeed() {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
var query = [
 'url=' + URL_TO_GET_RESULTS_FOR,
 'callback=runPagespeedCallbacks',
 'key=' + API_KEY,
].join('&');
s.src = API_URL + query;
document.getElementsByTagName("head")[0].insertBefore(s, null);
document.getElementById("page_speed").children[0].innerHTML = "Loading ...";
}

//Our JSONP callback. Checks for errors, then invokes our callback handlers.
function runPagespeedCallbacks(result) {
if (result.error) {
 var errors = result.error.errors;
 for (var i = 0, len = errors.length; i < len; ++i) {
   if (errors[i].reason == 'badRequest' && API_KEY == 'AIzaSyB-aMH9_2JJCYCSRL578Vnqiio6faclchE') {
     alert('Please specify your Google API key in the API_KEY variable.');
   } else {
     // NOTE: your real production app should use a better
     // mechanism than alert() to communicate the error to the user.
     alert(errors[i].message);
   }
 }
 return;
}

// Dispatch to each function on the callbacks object.
for (var fn in callbacks) {
 var f = callbacks[fn];
 if (typeof f == 'function') {
   callbacks[fn](result);
 }
}
}

callbacks.displayPageSpeedScore = function(result) {
var score = result.score;
// Construct the query to send to the Google Chart Tools.
var query = [
 'chtt=Page+Speed+score:+' + score,
 'chs=180x100',
 'cht=gom',
 'chd=t:' + score,
 'chxt=x,y',
 'chxl=0:|' + score,
].join('&');
var i = document.createElement('img');
i.src = CHART_API_URL + query;
document.getElementById("page_speed").insertBefore(i, null);
};

var RESOURCE_TYPE_INFO = [
{label: 'JavaScript', field: 'javascriptResponseBytes', color: 'e2192c'},
{label: 'Images', field: 'imageResponseBytes', color: 'f3ed4a'},
{label: 'CSS', field: 'cssResponseBytes', color: 'ff7008'},
{label: 'HTML', field: 'htmlResponseBytes', color: '43c121'},
{label: 'Flash', field: 'flashResponseBytes', color: 'f8ce44'},
{label: 'Text', field: 'textResponseBytes', color: 'ad6bc5'},
{label: 'Other', field: 'otherResponseBytes', color: '1051e8'},
];

callbacks.displayResourceSizeBreakdown = function(result) {
var stats = result.pageStats;
var labels = [];
var data = [];
var colors = [];
var totalBytes = 0;
var largestSingleCategory = 0;
for (var i = 0, len = RESOURCE_TYPE_INFO.length; i < len; ++i) {
 var label = RESOURCE_TYPE_INFO[i].label;
 var field = RESOURCE_TYPE_INFO[i].field;
 var color = RESOURCE_TYPE_INFO[i].color;
 if (field in stats) {
   var val = Number(stats[field]);
   totalBytes += val;
   if (val > largestSingleCategory) largestSingleCategory = val;
   labels.push(label);
   data.push(val);
   colors.push(color);
 }
}
// Construct the query to send to the Google Chart Tools.
var query = [
 'chs=300x140',
 'cht=p3',
 'chts=' + ['000000', 16].join(','),
 'chco=' + colors.join('|'),
 'chd=t:' + data.join(','),
 'chdl=' + labels.join('|'),
 'chdls=000000,14',
 'chp=1.6',
 'chds=0,' + largestSingleCategory,
].join('&');
var i = document.createElement('img');
i.src = 'http://chart.apis.google.com/chart?' + query;
document.getElementById("page_speed").insertBefore(i, null);
document.getElementById("page_speed").children[0].style.display = "none";
};